<?php

namespace app\admin\controller;

use think\Db;
use app\common\crypt\Crypt;
use app\service\user\UserService;
use app\model\User as UserModel;
use app\admin\validate\user\User as UserValidate;
use app\admin\validate\user\EditPassword as EditPasswordValidate;
use think\Session;

class User extends BaseController
{
    private static $parentMenu = 'user/index';

    /**
     * 用户列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $queryCode = $this->request->param('queryCode');
        $userService = new UserService();
        $list = $userService->getUserList($queryCode, $this->pageSize);
        $this->assign([
            'list' => $list,
            'page' => $list->render(),
            'empty' => '<tr><td colspan="9">暂无数据</td></tr>'
        ]);
        return $this->fetch('index');
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!isset($data['user_status'])) {
                $data['user_status'] = 0;
            }
            $validate = new UserValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), "2");
            }
            $model = new UserModel();
            $adminUser = Db::table('aya_user')->where('user_account', '=', 'admin')
            ->where('user_status', '<>', -1)->find();
            if ($adminUser && $data['user_account'] == $adminUser['user_account']) {
                $this->doRedirect('admin用户已存在！', "2");
            }
            $data['create_time'] = time();
            $help = new Crypt();
            $data['user_password'] = $help::encrypt($data['user_password']);
            $model->allowField(true)->save($data);
            $this->redirect('user/index');
        }
        $role = Db::table('aya_role')->where('role_status', '<>', -1)
            ->where('role_id', '<>', 1)
            ->order('role_id asc')
            ->select();
        $this->assign('role', $role);
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'user/add');
        return $this->fetch('add');
    }

    /**
     * 编辑用户
     * @return string
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $model = new UserModel();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $id = $data['user_id'];
            if (!isset($data['user_status'])) {
                $data['user_status'] = 0;
            }
            $user = Db::table('aya_user')->where("id", "=", $id)->find();
            if (!$user) {
                $this->doRedirect("找不到ID为" . $id . "的数据，请重试！", "2");
            }
            $validate = new UserValidate();
            if (!$validate->scene('edit')->check($data)) {
                $this->doRedirect($validate->getError(), "2");
            } else {
                if ($user['user_account'] == 'admin') {
                    $data['user_status'] = 1;
                    $data['user_account'] = 'admin';
                }
                $model->allowField(true)->save($data, ['id' => $id]);
                $this->redirect('user/index');
            }
        }
        $userId = $this->request->param('id');
        if ($userId < 0) {
            $this->doRedirect('参数错误，请重试！', "2");
        }
        $user = Db::table('aya_user')->where("id", "=", $userId)->find();
        if (!$user) {
            $this->doRedirect("找不到ID为{$userId}的数据，请重试！", "2");
        }
        $roleList = Db::table('aya_role')->where('role_status', '<>', -1)
                ->where('id', '<>', 1)
                ->order('id')
                ->select();
        $this->assign('roleList', $roleList);
        $this->assign("user", $user);
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'user/edit');
        return $this->view->fetch('edit');
    }

    /**
     * 删除用户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del()
    {
        $userId = $this->request->param('id');
        if (!isset($id)) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $model = new UserModel();
        $user = Db::table('aya_user')->where('id', '=', $userId)->find();
        if (!$user) {
            $this->doRedirect('找不到ID为' . $userId . '的数据，请重试！', '2');
        }
        if ($user['user_account'] == 'admin') {
            $this->doRedirect('该用户不能删除', '2');
        }
        $model->save(['user_status' => -1], ['id' => $userId]);
        $this->doRedirect('删除成功！', '1');
    }

    /**
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editPassword()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id');
            $model = new UserModel();
            $user = $model->where('id', '=', $id)->find();
            if (empty($user)) {
                $this->doRedirect('找不到ID为' . $id . '的数据，请重试！', '2');
            }
            $data = $this->request->post();
            $validate = new EditPasswordValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), '2');
            }
            $oldPassword = Crypt::decrypt($user['password']);
            if ($this->request->post('oldPassword') != $oldPassword) {
                $this->doRedirect('旧密码输入不正确', '2');
            }
            $password = Crypt::encrypt($this->request->post('newPassword'));
            $model->save(['password' => $password], ['id' => $id]);
            $this->doRedirect('修改成功', '1');
        }
        $session = new Session();
        $currentUser = $session->get($this->currentUser);
        $this->assign('id', $currentUser['id']);
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'user/editpassword');
        return $this->fetch('editpassword');
    }

    public function _empty()
    {
        $this->error('页面不存在');
    }
}